<template>
  <el-dialog
    :append-to-body="true"
    :close-on-click-modal="false"
    :title="title"
    top="5vh"
    :visible.sync="dialogFormVisible"
    width="666px"
    @close="close"
  >
    <div class="device-form-body">
      <el-form ref="form" label-width="110px" :model="form" :rules="rules">
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model.trim="form.deviceName" clearable max="20" />
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType">
          <el-select
            v-model="form.deviceType"
            class="full-select"
            clearable
            placeholder="请选择设备类型"
          >
            <el-option
              v-for="item in deviceType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备厂家" prop="deviceManufacturer">
          <el-select
            v-model="form.deviceManufacturer"
            class="full-select"
            clearable
            placeholder="请选择设备厂家"
          >
            <el-option
              v-for="item in deviceFactories"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备编码" prop="deviceNo">
          <el-input v-model.trim="form.deviceNo" clearable max="255" />
        </el-form-item>
        <el-form-item label="用户名" prop="user">
          <el-input v-model.trim="form.user" clearable max="20" />
        </el-form-item>
        <el-form-item label="密码" prop="passwd">
          <el-input
            v-model.trim="form.passwd"
            clearable
            max="20"
            show-password
          />
        </el-form-item>
        <el-form-item label="IP地址" prop="ip">
          <el-input v-model.trim="form.ip" clearable max="20" />
        </el-form-item>
        <el-form-item label="端口" prop="port">
          <el-input v-model.trim="form.port" clearable max="10" />
        </el-form-item>
        <el-form-item label="设备方向" prop="direction">
          <el-select
            v-model="form.direction"
            class="full-select"
            clearable
            placeholder="请选择设备方向"
          >
            <el-option
              v-for="item in deviceDirections"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="监控方向" prop="monitorDirection">
          <el-select
            v-model="form.monitorDirection"
            class="full-select"
            clearable
            placeholder="请选择监控方向"
          >
            <el-option
              v-for="item in monitorDirection"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备安装地址" prop="installAddress">
          <el-alert :closable="false" show-icon type="info">
            <slot name="description">
              地址格式：
              <strong>
                市/区县/乡镇街道/街路巷自然村/门牌号/小区名称/楼牌号/单元/层数/户室/地址ID
              </strong>
              <br />
              填写示例(没有的内容用'空'代替)：北京市/昌平区/史各庄街道/农学院北路/9号/港馨家园/领袖惠谷A区/空/空/空/东门向东50米
            </slot>
          </el-alert>
          <el-input
            v-model="form.installAddress"
            clearable
            max="200"
            placeholder="请输入居住地址"
            :rows="4"
            type="textarea"
          />
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model.trim="form.longitude" clearable max="30" />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model.trim="form.latitude" clearable max="30" />
        </el-form-item>
        <el-form-item label="街镇" prop="townNo">
          <el-select
            v-model="form.townNo"
            class="full-select"
            clearable
            placeholder="请选择街道"
            @change="changeTown"
          >
            <el-option
              v-for="item in townList"
              :key="item.id"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="小区" prop="areaNo">
          <!--          <el-input v-model.trim="form.areaNo" clearable max="50" />-->
          <el-select
            v-model="form.areaNo"
            class="full-select"
            clearable
            placeholder="请选择小区"
          >
            <el-option
              v-for="item in areaList"
              :key="item.id"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-select
            v-model="form.deptName"
            class="full-select"
            clearable
            placeholder="请选择部门"
          >
            <el-option
              :label="form.deptName"
              style="height: auto; padding: 0"
              :value="form.deptId"
            >
              <el-tree
                ref="tree"
                :data="treeList"
                default-expand-all
                :props="defaultProps"
                @node-click="handleNodeClick"
              />
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="摄像头编码" prop="cameraCode">
          <el-input v-model.trim="form.cameraCode" max="300" />
        </el-form-item>
        <el-form-item label="预览地址" prop="previewUrl">
          <el-input v-model.trim="form.previewUrl" max="300" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" max="200" />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button :loading="isSaving" type="primary" @click="save">
        确 定
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { saveOrEditDeviceInfo, getAreaList, getTownList } from '@/api/record'
  import { mapGetters } from 'vuex'
  import { getDeptTree } from '@/api/dept'
  const monitorDirection = [
    { label: '东向西', value: 1 },
    { label: '西向东', value: 2 },
    { label: '北向南', value: 3 },
    { label: '南向北', value: 4 },
    { label: '西南到东北', value: 5 },
    { label: '东北到西南', value: 6 },
    { label: '西北到东南', value: 7 },
    { label: '东南到西北', value: 8 },
    { label: '其他', value: 9 },
  ]
  export default {
    name: 'DeviceEdit',
    data() {
      const deptCheck = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请选择部门'))
        } else {
          callback()
        }
      }
      return {
        defaultProps: {
          children: 'childList',
          label: 'deptName',
        },
        treeList: [], // 部门树状结构
        deviceDirections: [
          { label: '入', value: '1' },
          { label: '出', value: '2' },
        ],
        deviceFactories: [
          { label: '赛合摄像', value: 'dahua' },
          { label: '赛合门禁', value: 'yushi' },
        ],
        monitorDirection: monitorDirection,
        form: {
          deviceName: '',
          deviceType: '',
          deviceNo: '',
          ip: '',
          direction: '',
          installAddress: '',
          longitude: '',
          latitude: '',
          townNo: '',
          areaNo: '',
          cameraCode: '',
          previewUrl: '',
          remark: '',
          user: 'admin',
          passwd: 'admin123',
          port: 80,
          deviceManufacturer: '',
          deptId: '',
          deptName: '',
          monitorDirection: null, // 监控方向
        },
        rules: {
          deviceName: [
            { required: true, trigger: 'blur', message: '请输入设备名称' },
          ],
          deviceType: [
            { required: true, trigger: 'change', message: '请选择设备类型' },
          ],
          deviceManufacturer: [
            { required: true, trigger: 'change', message: '请选择设备厂家' },
          ],
          deviceNo: [
            { required: true, trigger: 'blur', message: '请输入设备编码' },
          ],
          ip: [{ required: true, trigger: 'blur', message: '请输入ip' }],
          user: [{ required: true, trigger: 'blur', message: '请输入用户名' }],
          passwd: [{ required: true, trigger: 'blur', message: '请输入密码' }],
          port: [{ required: true, trigger: 'blur', message: '请输入端口' }],
          deptId: [{ required: true, validator: deptCheck, trigger: 'blur' }],
          direction: [
            { required: true, trigger: 'change', message: '请选择设备方向' },
          ],
          monitorDirection: [
            { required: true, trigger: 'change', message: '请选择监控方向' },
          ],
          installAddress: [
            {
              required: true,
              trigger: 'change',
              message: '请输入设备安装地址',
            },
          ],
          longitude: [
            { required: true, trigger: 'change', message: '请输入经度' },
          ],
          latitude: [
            { required: true, trigger: 'change', message: '请输入纬度' },
          ],
          townNo: [
            { required: true, trigger: 'change', message: '请选择街道' },
          ],
          areaNo: [
            { required: true, trigger: 'change', message: '请选择小区' },
          ],
          cameraCode: [
            { required: true, trigger: 'change', message: '请输入摄像头编码' },
          ],
          previewUrl: [
            { required: true, trigger: 'change', message: '请输入预览地址' },
          ],
        },
        title: '',
        dialogFormVisible: false,
        townList: [],
        areaList: [],
        isSaving: false,
      }
    },
    computed: {
      ...mapGetters({
        deviceType: 'dict/deviceType',
      }),
    },
    created() {
      // 获取街道列表
      this._getTownList()
      this.getDeptTree()
    },
    methods: {
      handleNodeClick(node) {
        this.form.deptName = node.deptName
        this.form.deptId = node.id
      },
      _getTownList() {
        getTownList()
          .then((res) => {
            if (
              res.status === 0 &&
              Array.isArray(res.data) &&
              res.data.length > 0
            ) {
              this.townList = res.data
            }
          })
          .catch((e) => {
            console.log(e)
          })
      },
      _getAreaList(townId) {
        getAreaList(townId)
          .then((res) => {
            if (res.status === 0 && Array.isArray(res.data)) {
              this.areaList = res.data
            }
          })
          .catch((e) => {
            console.log(e)
          })
      },
      changeTown(code) {
        let id = ''
        for (let i = 0; i < this.townList.length; i++) {
          if (this.townList[i].code === code) {
            id = this.townList[i].id
            break
          }
        }
        this.form.areaNo = ''
        this.areaList = []
        this._getAreaList(id)
      },
      showEdit(row) {
        if (!row) {
          this.title = '添加设备'
        } else {
          this.title = '修改设备信息'
          this.form = Object.assign({}, row)
        }
        if (this.townList.length > 0) {
          this._getAreaList(this.townList[0].id)
        }
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
        this.areaList = []
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            try {
              this.isSaving = true
              const res = await saveOrEditDeviceInfo(this.form)
              let successMsg = '设备添加成功'
              let errorMsg = '设备添加失败'
              if (this.form.id) {
                successMsg = '设备修改成功'
                errorMsg = '设备修改成功'
              }
              if (res && res.status === 0) {
                this.$baseMessage(
                  res.msg || successMsg,
                  'success',
                  'vab-hey-message-success'
                )
                this.$emit('fetch-data')
                this.close()
              } else {
                this.$baseMessage(
                  res ? res.msg : errorMsg,
                  'error',
                  'vab-hey-message-error'
                )
              }
            } catch (e) {
              console.log(e)
              this.$baseMessage(
                e.message || '操作失败',
                'error',
                'vab-hey-message-error'
              )
            }
            this.isSaving = false
          }
        })
      },
      async getDeptTree() {
        try {
          const res = await getDeptTree(this.queryForm)
          if (res && Array.isArray(res.data)) {
            this.treeList = res.data
          }
        } catch (e) {
          console.log(e)
        }
      },
    },
  }
</script>
<style lang="css">
  .full-select {
    width: 100%;
  }
  .device-form-body {
    height: calc(100vh - 250px);
    overflow: auto;
    padding-right: 10px;
  }
</style>
